package cn.enilu.flash.mobile.controller;

import cn.enilu.flash.bean.entity.shop.Track;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.shop.TrackService;
import cn.enilu.flash.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user/track")
public class TrackController {
    @Autowired
    private TrackService trackService;

    /**
     * 添加足迹
     * @param idGoods
     * @return
     */
    @RequestMapping(value = "/add/{idGoods}",method = RequestMethod.POST)
    public Object add(@PathVariable("idGoods") Long idGoods){
        Date date = new Date();
        Long idUser = JwtUtil.getUserId();
        Track old = trackService.get(Lists.newArrayList(
                SearchFilter.build("idUser",idUser),
                SearchFilter.build("idGoods",idGoods)));
        if(old!=null){
            old.setModifyTime(date);
            trackService.update(old);
            return Rets.success();
        }
        Track track = new Track();
        track.setIdUser(idUser);
        track.setIdGoods(idGoods);
        trackService.insert(track);
        return Rets.success();
    }

    /**
     * 获取前50足迹
     * @param
     * @return
     */
    @RequestMapping(value = "/getListTop50",method = RequestMethod.GET)
    public Object getListTop50(){
        Long idUser = JwtUtil.getUserId();
        SearchFilter searchFilter = SearchFilter.build("idUser", idUser);
        Sort sort = Sort.by(Sort.Direction.DESC,"modifyTime");
        List<Track> list = trackService.queryAll(searchFilter,sort);
        if(list.size()>=50){
            list = list.subList(0,50);
        }
        return Rets.success(list);
    }
}
